﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;

namespace BCDto.Utils
{
    /// <summary>
    /// 文件类型验证
    /// </summary>
    public class FileTypeAttribute:ValidationAttribute
    {
        private string[] fileSuffixes = new string[] { "mp4", "Wav" };
        private string suffix;

        public FileTypeAttribute(string[] fileSuffixes)
        {
            this.fileSuffixes = fileSuffixes;
        }

        public override bool IsValid(object value)
        {
            string vStr = value.ToString();
            List<string> urls = new List<string>();
            urls = vStr.IndexOf(',') > -1 ? vStr.Split(',').ToList() : new List<string> { vStr };

            foreach (string url in urls)
            {
                if (!ValidationFileSuffix(url))
                {
                    ErrorMessage = string.Format("{0} 是不被接收的文件类型,请重新上传.", url.Substring(url.LastIndexOf('.') + 1));
                    return false;
                }
            }
            return true;
        }
        private bool ValidationFileSuffix(string fileUrl)
        {
            suffix = fileUrl.Substring(fileUrl.LastIndexOf('.')+1);
            return fileSuffixes.Contains(suffix);
        }

        public string Suffix(string fileUrl)
        {
            return fileUrl.Substring(fileUrl.LastIndexOf('.') + 1);
        }
    }
}
